import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import {Api} from "../../providers/api/api";
import {User} from "../../providers/user/user";

/**
 * Generated class for the PlanDetailPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-plan-detail',
  templateUrl: 'plan-detail.html'
})
export class PlanDetailPage {
  planDetail: any;
  content: string;
  favorite: any;
  private networkErrorString: string;

  constructor(public navCtrl: NavController,
              public api: Api,
              public user: User,
              public toastCtrl: ToastController,
              public navParams: NavParams) {
    this.planDetail = navParams.data;
    this.content = this.planDetail.content.replace(/[\n\r]/g, '<br>');
    this.hitsAdd();
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad PlanDetailPage');
  }

  star() {
    this.favorite = {
      'customerName': this.user._user.accountName,
      'favoritePlan': this.planDetail.id
    };
    let seq = this.api.post('favorites', this.favorite).share();
    seq.subscribe((res: any) => {
      console.log(res)
      // If the API returned a successful response, mark the user as logged in
      if (res) {
        this.showToast("恭喜你,收藏成功！").present();
      } else {
        this.showToast().present();
      }
    }, err => {
      if (err.status == 400) {
        this.showToast("您已收藏了，不要重复收藏！").present();
      } else {
        this.showToast().present();
      }
      console.error('ERROR', err);
    });
  }

  hitsAdd() {
    if (this.planDetail.subType === undefined) {
      this.favorite = {
        'id': this.planDetail.id
      };
      let seq = this.api.put('plans/hits', this.favorite).share();
      seq.subscribe((res: any) => {
        console.log(res)
      }, err => {
        console.warn('ERROR', err);
      });
    }
  }

  showToast(msg?) {
    return this.toastCtrl.create({
      message: msg ? msg : this.networkErrorString,
      duration: 1000,
      position: 'top'
    });
  }
}
